<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card class="tree-card">
        <!-- 用了一个行列布局 -->
        <TreeTools
          :node-data="company"
          :is-root="true"
          @addDepartment="addDepartment"
        />

        <hr>

        <!-- 用一个树形组件存放部门 -->
        <el-tree
          :data="treeData"
          default-expand-all
        >
          <!-- 这里就是自定义节点渲染插槽 -->
          <template #default="obj">
            <TreeTools
              :node-data="obj.data"
              @delDepartment="getDepartments"
              @addDepartment="addDepartment"
              @editDepartment="editDepartment"
            />
          </template>
        </el-tree>
      </el-card>
      <AddDept
        ref="addDept"
        :show-dialog.sync="showDialog"
        :node-data="nodeData"
        @addDepartment="getDepartments"
      />
    </div>
  </div>
</template>

<script>
import TreeTools from './components/tree-tools.vue'
import AddDept from './components/add-dept.vue'
import { getDepartments } from '@/api/department'
import { listToTreeData } from '@/utils'
export default {
  components: {
    TreeTools,
    AddDept
  },
  data() {
    return {
      company: {
        name: '江苏传智播客教育科技股份有限公司',
        manager: '负责人',
        id: ''
      },
      treeData: [],
      showDialog: false,
      nodeData: {}
    }
  },
  async created() {
    this.getDepartments()
  },
  methods: {
    async getDepartments() {
    // const res = await getDepartments()
    // this.treeData = res.depts
      const { depts } = await getDepartments()
      // 封装一个函数, 可以讲传入的后台数据转换成树形返回出来
      this.treeData = listToTreeData(depts, '')
    },
    addDepartment(nodeData) {
      this.showDialog = true
      this.nodeData = nodeData
    },
    editDepartment(nodeData) {
      // 这里是编辑弹窗
      // 所以需要回显数据
      // 直接调用弹窗子组件的函数
      this.$refs.addDept.getDeptDetail(nodeData.id)
      this.nodeData = nodeData
      this.showDialog = true
    }
  }
}
</script>

<style scoped>
.tree-card {
  padding: 30px  140px;
  font-size:14px;
}
</style>
